<?php

namespace frontend\controllers;

use Yii;
use frontend\models\User;
use frontend\models\userExtend;
use frontend\models\UserWithdraw;
use frontend\models\UserCharge;
use common\helpers\FileHelper;
use frontend\models\Product;
use frontend\models\Order;
use frontend\models\Bank;
use frontend\models\ProductPrice;
use frontend\models\Coupon;
use frontend\models\UserCoupon;
use frontend\models\DataAll;
use frontend\models\UserAccount;
class UserController extends \frontend\components\Controller
{
    public function beforeAction($action)
    {
        if (user()->isGuest) {
            $this->redirect(['site/login']);
            return false;            
            // $wx = session('wechat_userinfo');
            // if (!empty($wx)) {
            //     $user = User::find()->where(['open_id' => $wx['openid']])->one();
            //     $user->login(false);
            // } else {
            //     $code = get('code');
            //     if (empty($code)) {
            //         $this->redirect(['/wechart.php']);
            //         return false;
            //     } else {
            //         User::registerUser($code);
            //     }
            // }
        }
        if (!parent::beforeAction($action)) {
            return false;
        } else {
            return true;
        }
    }
    
    /**
     * @authname  个人中心
     */
    public function actionIndex()
    {
        $this->view->title = '我的个人中心';
        //每个用户自动生成邀请二维码
        // User::isHaveUserCode();

        $user = User::findModel(u()->id);
        //微信分享参数
        require_once Yii::getAlias('@vendor/wx/WxTemplate.php');
        // $wxTemplate = new \WxTemplate();
        // $wxConfig = $wxTemplate->getWxConfig('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
        $time_day = date("Y-m-d",strtotime("+1 day")).' 00:00:00';
        // test($time_day);
        $orderProfit = Order::find()->where(['user_id' => u()->id])->andWhere(['>', 'updated_at', date('Y-m-d 00:00:00')])->andWhere(['<', 'updated_at', $time_day])->select(['SUM(profit) profit'])->one()->profit;
        $orders = Order::find()->where(['user_id' => u()->id])->andWhere(['>', 'updated_at', date('Y-m-d 00:00:00')])->andWhere(['<', 'updated_at', $time_day])->count();
        // test($orders);

        return $this->render('index', compact('user', 'manager','orderProfit', 'orders'));
    }

    public function actionWithDraw()
    {
        $this->view->title = '提现';
        $this->layout = 'empty';
        $model = User::findModel(u()->id);
        $userAccount = UserAccount::find()->where(['user_id' => u()->id])->one();
        if (empty($userAccount)) {
            $userAccount = new UserAccount();
        }

        $userWithdraw = new UserWithdraw(['scenario' => 'withdraw']);
        if ($userWithdraw->load(post())) {
            if(date('G') < 10 || date('G') > 16 || date('w') == 0 || date('w') == 6){
                return error('请在规定时间提现'); 
            }
            $userWithdraws = UserWithdraw::find()->where(['user_id' => u()->id])->andWhere(['>', 'created_at', date('Y-m-d 00:00:00', time())])->andWhere(['<>', 'op_state', UserWithdraw::OP_STATE_DENY])->select('SUM(amount) amount')->one()->amount;
            if($userWithdraws > 20000) {
                return error('单日提现累计不能超过20000');
            }

            $order = Order::find()->where(['user_id' => u()->id, 'order_state' => Order::ORDER_THROW])->one();
            if(empty($order)) {
                return error('没有交易订单无法提现');
            }

            if($model->account < 0 || $model->blocked_account < 0 || $model->state == User::STATE_INVALID) {
                return error('您的账户暂时不能提现');
            }
            if (!$userWithdraw->validate()) {
                return error($userWithdraw);
            }
            $userAccount->load(post());
            $bank = Bank::find()->where(['number' => $userAccount->bank_name])->one();
            if (empty($bank)) {
               return error('找不到这个银行名称！'); 
            }
            $userAccount->realname = $userAccount->bank_user;
            $userAccount->bank_mobile = u()->mobile;
            $userAccount->id_card = 'xx';
            $userAccount->user_id = u()->id;
            //用户账户表处理
            if ($userAccount->validate()) {
                $userAccount->save();
                //验证交易密码
                $model->scenario = 'withdraw';
                $model->load(post());
                if ($model->validate()) {
                    $userWithdraw->user_id = u()->id;
                    $userWithdraw->out_sn = u()->id . date("YmdHis") . rand(1000, 9999);
                    $userWithdraw->account_id = $userAccount->id;
                    if ($userWithdraw->insert(false)) {
                        $model->account -= $userWithdraw->amount; 
                        $model->save(false);
                        return success('提交申请成功');
                    }
                }
                return error($model);
            } else {
                return error($userAccount);
            }
        }

        return $this->render('withDraw', compact('userAccount', 'userWithdraw', 'model'));
    }

    /**
     * @authname  交易记录界面
     */
    public function actionTransDetail()
    {
        $this->view->title = '交易记录';
        $this->layout = 'empty';
        $query = Order::find()->where(['order_state' => Order::ORDER_THROW, 'user_id' => u()->id])->with('product')->orderBy('order.updated_at DESC');
        // 每页显示3条
        $data = $query->paginate(5);
        // 查询总数量
        $count = $query->totalCount;
        // 总共多少页
        $pageCount = $count / 5;
        // 判断是不是整数
        if (!is_int($pageCount)) {
            $pageCount = (int)$pageCount + 1;
        }
        // 点击加载更多显示的页面
        if (get('p')) {

            return success($this->renderPartial('_transDetail', compact('data')), $pageCount);
        }
        return $this->render('transDetail', compact('count', 'pageCount', 'data'));
    }
      /**
     * @authname  我的账单页面
     */
    public function actionMyBill()
    {
        $this->view->title = '我的账单';
        $this->layout = 'empty';
        // 查询信息
        $query = UserCharge::find()->where(['charge_state' => UserCharge::CHARGE_STATE_PASS, 'user_id' => u()->id])->orderBy('created_at DESC');
        // 每页显示3条
        $data = $query->paginate(5);
        // 查询总数量
        $count = $query->totalCount;
        // 总共多少页
        $pageCount = $count / 5;
        // 判断是不是整数
        if (!is_int($pageCount)) {
            $pageCount = (int)$pageCount + 1;
        }
        if (get('p')) {

            return success($this->renderPartial('_myBill', compact('data')), $pageCount);
        }
        return $this->render('myBill', compact('count', 'pageCount', 'data'));
    }
    public function actionOutMoney()
    {
        $this->view->title = '出金记录';

        $query = UserWithdraw::find()->where(['user_id' => u()->id])->orderBy('created_at DESC');
        $data = $query->paginate(5);
        $pageCount = $query->totalCount / 5;
        if (!is_int($pageCount)) {
            $pageCount = (int)$pageCount + 1;
        }
        if (get('p')) {

            return success($this->renderPartial('_outMoney', compact('data')), $pageCount);

        }

        return $this->render('outMoney', compact('count', 'pageCount', 'data'));
    }

    public function actionSetting()
    {
        $this->view->title = '个人设置';

        return $this->render('setting');
    }

    public function actionMaintain()
    {
        $this->view->title = '维护中';
        $this->layout = 'empty';
        return $this->render('/site/maintain');
    }

    public function actionMyOffline()
    {
        $this->view->title = '名下用户记录';
        //如果是经纪人
        if (u()->is_manager != User::IS_MANAGER_YES) {
            return $this->redirect('/site/wrong');
        }
        //名下的用户
        $idArr = User::getUserOfflineId();
        $idArr = array_merge($idArr[0], $idArr[1]);
        $query = User::find()->where(['state' => User::STATE_VALID])->andWhere(['in', 'id', $idArr])->orderBy('created_at DESC');
        $data = $query->paginate(PAGE_SIZE);

        return $this->render('myOffline', compact('data'));
    }


    //请求更新订单钱数
    public function actionAjaxUpdateCharge()
    {
        $data = post('data');
        if (is_int($data['amount']) || $data['amount'] <= 0) {
            return error('金额参数非法！');
        }
        $userCharge = UserCharge::find()->where(['charge_state' => UserCharge::CHARGE_STATE_WAIT, 'user_id' => u()->id, 'id' => $data['id']])->one();
        if (!empty($userCharge)) {
            $userCharge->amount = floatval($data['amount']);
            $userCharge->trade_no = u()->id . date("YmdHis") . rand(1000, 9999);
            if ($userCharge->save()) {
                return success(1);
                //微信生成订单
                require Yii::getAlias('@vendor/WxPayPubHelper/WxPayPubHelper.php');
                $jsApi = new \JsApi_pub();
                $openid = u()->open_id;
                $unifiedOrder = new \UnifiedOrder_pub();
                $unifiedOrder->setParameter("openid", $openid);//商品描述
                $unifiedOrder->setParameter("body", "微盘充值");//商品描述
                $unifiedOrder->setParameter("out_trade_no", $userCharge->trade_no);//商户订单号
                $unifiedOrder->setParameter("total_fee", $userCharge->amount * 100);//总金额
                $unifiedOrder->setParameter("notify_url", "http://" . $_SERVER['HTTP_HOST'] . "/site/ajax-update-status");//通知地址
                $unifiedOrder->setParameter("trade_type", "JSAPI");//交易类型
                $prepay_id = $unifiedOrder->getPrepayId();
                $jsApi->setPrepayId($prepay_id);
                $jsApiParameters = $jsApi->getParameters();
                return success($jsApiParameters);
            }
        }
        return error('数据异常！');
    }

    public function actionTt()//测试充值
    {
        $data = post('data');
        $userCharge = UserCharge::find()->where(['charge_state' => UserCharge::CHARGE_STATE_WAIT, 'user_id' => u()->id, 'id' => $data['id']])->one();
        if (!empty($userCharge)) {
            // test($userCharge->amount);
            $userCharge->charge_state = 2;
            if ($userCharge->save()) {
                $user = User::findOne($userCharge->user_id);
                $user->account += $userCharge->amount;
                if ($user->save()) {
                    return success('成功');
                }
            } else {
                return error($userCharge);
            }
        }
        return error('失败！');
    }

    public function actionWrong()
    {
        $this->view->title = '错误';
        return $this->render('wrong');
    }
    /**
     * @authname  代金券
     */
    public function actionExperience()
    {
        $this->view->title = '代金劵';
        $this->layout = 'empty';
        $userCoupons = UserCoupon::find()->andWhere(['use_state' => UserCoupon::USE_STATE_WAIT, 'user_id' => u()->id])->andWhere(['>', 'number', 0])->andWhere(['>', 'valid_time', self::$time])->joinWith(['coupon'])->orderBy('amount ASC')->all();
        return $this->render('experience', compact('userCoupons'));
    }

    public function actionRecharge()
    {     
        $this->view->title = '充值';
        $this->layout = 'empty';
        return $this->render('recharge', compact('code'));
    }


    public function actionPay()
    {
        $amount = post('amount', '0.01');
        $this->layout = 'empty';
        $this->view->title = '安全支付';
        // $amount = 0.01;
        switch (post('type', 2)) {
            case '1':
                $src = UserCharge::payYifuPay($amount, '1');
                if($src){
                    header("Location:$src");
                    exit();
                }else{
                    return $this->redirect(['site/wrong']);
                }
                break;
            default:
                return $this->render('zfpay', compact('info'));
                break;
        }
    }

    public function actionPassword()
    {
        $this->view->title = '修改密码';
        $this->layout = 'empty';
        $model = User::findOne(u('id'));
        $model->scenario = 'password';

        if ($model->load($_POST)) {
            if ($model->validate()) {
                $model->password = $model->newPassword;
                if ($model->hashPassword()->update()) {
                    return $this->redirect(['index']);
                } else {
                    return error($model);
                }
            } else {
                return error($model);
            }
        }

        return $this->render('password', compact('model'));
    }

    public function actionChangePhone()
    {
        $this->view->title = '修改手机号';

        $model = User::findOne(u('id'));
        $model->scenario = 'changePhone';

        if ($model->load($_POST)) {
            if ($model->validate()) {
                $model->username = $model->mobile;
                if ($model->update()) {
                    return $this->redirect(['user/index']);
                } else {
                    return error($model);
                }
            } else {
                return error($model);
            }
        }
        $model->mobile = null;
        return $this->render('changePhone', compact('model'));
    }

    public function actionLogout()
    {
        user()->logout(false);

        return $this->redirect('/site/index');
    }

}
